package com.eg366.nioLearn.baseSocket.chapter03;

import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 基于“定界符”的成帧方法
 * 
 * @author user
 * 
 */
public class DelimFramer implements Framer {

	private InputStream in;
	private static final byte DELIMITER = 10; // \n
	
	public DelimFramer(InputStream in) {
		this.in = in;
	}

	/**
	 * 添加成帧信息并将指定的消息输出到指定流
	 */
	@Override
	public void frameMsg(byte[] message, OutputStream out) throws IOException {
		for (byte b : message) {
			/* 检测是否包含定界符 */
			if (b == DELIMITER) {
				throw new IOException("Message contains delimiter");
			}
		}
		out.write(message);
		out.write(DELIMITER);
		out.flush();
	}

	/**
	 * 扫描指定的流，从中抽取下一条消息
	 */
	@Override
	public byte[] nextMsg() throws IOException {
		ByteArrayOutputStream messageBuffer = new ByteArrayOutputStream();
		int nextByte;

		/* 读取流中每一个字节，直到遇到定界符为止 */
		while ((nextByte = in.read()) != DELIMITER) {
			/* 在遇到定界符之前就到了流的终点 */
			if (nextByte == -1) {
				if (messageBuffer.size() == 0) {
					return null;
				} else {
					throw new EOFException(
							"Non-empty message without delimiter");
				}
			}
			messageBuffer.write(nextByte);
		}
		return messageBuffer.toByteArray();
	}

}
